﻿using System;
using Ewk.Math.Numerics;

namespace Ewk.Math.ComputationTypes.Computables
{
    class ComputableComplex : Computable<Complex>
    {
        #region Constructors
        public ComputableComplex()
        {
        }

        public ComputableComplex(Complex value)
            : base(value)
        {
        }
        #endregion

        #region ComputableBase implementations
        public override Computable<Complex> Add(Computable<Complex> other)
        {
            if (other !=null)
            {
                Value += other.Value;
            }

            return this;
        }

        public override Computable<Complex> Subtract(Computable<Complex> other)
        {
            if (other != null)
            {
                Value -= other.Value;
            }

            return this;
        }

        public override Computable<Complex> Multiply(Computable<Complex> other)
        {
            if (other != null)
            {
                Value *= other.Value;
            }
            else
            {
                Value = Factory.Zero.Value;
            }

            return this;
        }

        public override Computable<Complex> Divide(Computable<Complex> other)
        {
            if (other == null)
            {
                throw new DivideByZeroException();
            }

            Value /= other.Value;
            return this;
        }

        public override Computable<Complex> Sqrt()
        {
            Value = Complex.Sqrt(Value);
            return this;
        }

        public override Computable<Complex> Pow(Computable<Complex> power)
        {
            Value = power == null 
                ? Factory.One.Value
                : Complex.Pow(Value, power.Value);

            return this;
        }

        #endregion

        public override bool AlmostEquals(Computable<Complex> other)
        {
            if (ReferenceEquals(null, other)) return false;

            return System.Math.Round(System.Math.Abs(Value.Real - other.Value.Real), 14) < double.Epsilon &&
                   System.Math.Round(System.Math.Abs(Value.Imaginary - other.Value.Imaginary), 14) < double.Epsilon;
        }
    }
}